package cn.kgc.springboot.service.impl;

import cn.hutool.crypto.SecureUtil;
import cn.kgc.springboot.common.CodeMsg;
import cn.kgc.springboot.dto.UserDTO;
import cn.kgc.springboot.entity.*;
import cn.kgc.springboot.mapper.*;
import cn.kgc.springboot.util.LayTable;
import cn.kgc.springboot.util.TreeUtil;
import cn.kgc.springboot.vo.MenuVo;
import cn.kgc.springboot.vo.UserVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.kgc.springboot.service.UserService;
import org.apache.catalina.security.SecurityUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 */
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User>implements UserService{

    @Autowired
    private  UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private RoleMapper  roleMapper;

    @Autowired
    private  RolePerMapper rolePerMapper;

    @Autowired
    private  MenuMapper menuMapper;

    @Override
    public LayTable getAll(String loginName, Integer page, Integer limit) {

        Page<User> userPage = new Page<>(page, limit);
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq(loginName!=null&&!loginName.equals(""), "login_name", loginName);
        userMapper.selectPage(userPage, userQueryWrapper);

        // 获取用户数据记录总数
        long total = userPage.getTotal();
        List<User> records = userPage.getRecords();

        //  user  -> uservo
        ArrayList<UserVO> userVOS = new ArrayList<>();
        // 遍历records
        for (User user : records) {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            userVOS.add(userVO);
        }

        System.out.println("userVOS = " + userVOS);

        //   遍历userVOS    填充 uservo中的角色信息

        for (UserVO userVO : userVOS) {
            //获取用户id
            Integer id = userVO.getId();

            //根据用户id 查询用户角色信息
            QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<>();
            userRoleQueryWrapper.eq("user_id", id);
            List<UserRole> userRoles = userRoleMapper.selectList(userRoleQueryWrapper);

            //userRoles  当前用户对应的角色相关信息  user_id  role_id  创建集合 封装用户角色信息   id  name
            ArrayList<Role> roles = new ArrayList<>();
            for (UserRole userRole : userRoles) {
                //获取当前用户的角色id
                Integer roleId = userRole.getRoleId();
                //根据角色id 查询角色表  获取角色详细信息
                Role role = roleMapper.selectById(roleId);
                roles.add(role);
            }

            // 将roles 列表 设置到uservo对象中
            userVO.setRoles(roles);
        }
        return new LayTable().setMsg(CodeMsg.LAY_SUCCESS.getMsg()).setCode(CodeMsg.LAY_SUCCESS.getCode()).setCount(total).setData(userVOS);
    }

    @Override
    public LayTable deleteById(Integer[] ids) {

        List<Integer> intIds = Arrays.asList(ids);
        //  根据id 删除用户信息
        userMapper.deleteBatchIds(intIds);
        // 根据id 删除用户对应的角色信息   用户角色关联表
        for (Integer intId : intIds) {
            QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<>();
            userRoleQueryWrapper.eq("user_id", intId);
            userRoleMapper.delete(userRoleQueryWrapper);
        }

        return new LayTable().setCode(CodeMsg.SUCCESS.getCode()).setMsg(CodeMsg.SUCCESS.getMsg());
    }

    @Override
    public LayTable addUser(UserDTO userDTO) {

        //  验证用户名 是否存在
        String loginName = userDTO.getLoginName();
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("login_name", loginName);
        User usr = userMapper.selectOne(userQueryWrapper);

        if(ObjectUtils.isNull(usr)){ // 用户名不存在  添加用户信息
            //  1. 添加用户信息
            User user = new User();
            BeanUtils.copyProperties(userDTO, user);
            //设置默认密码
            user.setPassword(SecureUtil.md5("12345"));
            userMapper.insert(user);
            // 获取插入用户自增的id  用于用户角色信息的添加
            Integer userId = user.getId();

            //  2.添加用户对应的角色信息    user_id  role_id
            Integer[] roleIds = userDTO.getRoleIds();
            for (Integer roleId : roleIds) {
                UserRole userRole = new UserRole();
                userRole.setUserId(userId);
                userRole.setRoleId(roleId);
                userRoleMapper.insert(userRole);
            }

            return new LayTable().setMsg(CodeMsg.SUCCESS.getMsg()).setCode(CodeMsg.SUCCESS.getCode());
        }

            return new LayTable().setMsg(CodeMsg.ERROR.getMsg()).setCode(CodeMsg.ERROR.getCode());

    }

    @Override
    public LayTable updateUser(UserDTO userDTO) {

       //更新用户信息
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
        userUpdateWrapper.eq("login_name", user.getLoginName()) ;
        userMapper.update(user,userUpdateWrapper);

        // 删除用户对应的角色信息  查询用户对用的id
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("login_name", user.getLoginName());
        User user1 = userMapper.selectOne(userQueryWrapper);
        //获取用户id
        Integer userId = user1.getId();
        //  根据用户的id  删除 对应的角色信息   用户角色关联表
        QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<>();
        userRoleQueryWrapper.eq("user_id", userId);
        userRoleMapper.delete(userRoleQueryWrapper);

        //  添加用户新的角色信息   获取用户角色id
        Integer[] roleIds = userDTO.getRoleIds();
        for (Integer roleId : roleIds) {
            UserRole userRole = new UserRole();
            userRole.setUserId(userId);
            userRole.setRoleId(roleId);
            userRoleMapper.insert(userRole);
        }

        return new LayTable().setMsg(CodeMsg.SUCCESS.getMsg()).setCode(CodeMsg.SUCCESS.getCode());
    }

    @Override
    public LayTable loadMenu(Integer userId) {

        //根据用户id  查询用户角色id
        List<UserRole> userRoles = userRoleMapper.selectList(new QueryWrapper<UserRole>().eq("user_id", userId));

        List<Integer> roleIds = userRoles.stream().map(userRole -> {
            return userRole.getRoleId();
        }).collect(Collectors.toList());

        // 根据用户的角色id 查询对应的权限id
        QueryWrapper<RolePer> rolePerQueryWrapper = new QueryWrapper<>();
        rolePerQueryWrapper.in("role_id", roleIds);
        List<RolePer> rolePers = rolePerMapper.selectList(rolePerQueryWrapper);

        List<Integer> perIds = rolePers.stream().map(rolePer -> {
            return rolePer.getPerId();
        }).collect(Collectors.toList());


        // 根据权限id 查询 权限的详细信息  Menu
        List<Menu> menus = menuMapper.selectList(new QueryWrapper<Menu>().in("id", perIds).eq("type", 0));

        // Menu  - > MenuVo

        List<MenuVo> MenuVos = menus.stream().map(menu -> {
            MenuVo menuVo = new MenuVo();
            menuVo.setId(menu.getId());
            menuVo.setPid(menu.getPid());
            menuVo.setName(menu.getName());
            menuVo.setIcon(menu.getIcon());
            menuVo.setUrl(menu.getHref());
            return menuVo;
        }).collect(Collectors.toList());

        //   MenuVo    ->   tree  -> TreeUtil

        List<MenuVo> menuVoList = TreeUtil.toTree(MenuVos, 0);

        // 将数据封装成 LayTable
        return new LayTable().setCode(CodeMsg.SUCCESS.getCode()).setMsg(CodeMsg.SUCCESS.getMsg()).setData(menuVoList);
    }
}




